package com.tanhua.dubbo.api.impl.mongo;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.AskerVo;
import com.tanhua.domain.vo.TodayBestVo;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.TanhuaApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TanhuaApiImpl implements TanhuaApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserInfoApi userInfoApi;
    @Autowired
    private SettingsApi settingsApi;
    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public void idunLove(Long id, Long myid) {
        //获取userlovestate,判断是否访问的是语音的love
        Query queryIsLove = new Query(Criteria.where("userId").is(myid));
        UserLoveState loveState = mongoTemplate.findOne(queryIsLove, UserLoveState.class);
        if (loveState.getIslove() == 1) {
          /*  //查询临时拉黑语音表修改语音拉黑状态,更新总语音表状态
            Query queryBlackList = new Query(Criteria.where("type").is(2));
            //查出那条状态为2的数据
            UserSoundBlackList balcksound = mongoTemplate.findOne(queryBlackList, UserSoundBlackList.class, "user_soundBlackList_" + myid);*/
            String soundId = redisTemplate.opsForValue().get("Sound_Linshi_" + myid);
            if (soundId != null) {
                Query querypub=new Query(Criteria.where("soundId").is(new ObjectId(soundId)));
                System.out.println("进来了type2");
                Update update = new Update();
                update.set("type", 1);
                mongoTemplate.updateFirst(querypub, update, "user_soundBlackList_" + myid);
                //删除状态为3的数据
                Query queryBlackList2 = new Query(Criteria.where("soundId").is(new ObjectId(soundId)).and("type").is(3));
                mongoTemplate.remove(queryBlackList2, "user_soundBlackList_" + myid);
                //查出被拉黑的objectId，修改总表为状态0可以重新获取
                Update updatePublishSound = new Update();
                updatePublishSound.set("state", 0);
                Query queryPublishSound = new Query(Criteria.where("id").is(new ObjectId(soundId)));
                mongoTemplate.updateFirst(queryPublishSound, updatePublishSound, UserSound.class);
            } else {
                System.out.println("进来了type3");
                //如果blacksound的type为2为空则查找type为3，从redis获取,改变本表状态
                String objectId = redisTemplate.opsForValue().get("user_soundRepeat_" + myid);
                System.out.println("redisObjectId" + objectId);
                Query query = new Query(Criteria.where("soundId").is(new ObjectId(objectId)));
                Update update = new Update();
                update.set("type", 1);
                mongoTemplate.updateFirst(query, update, "user_soundBlackList_" + myid);
                //改变总表中的语音状态
                Query querypublish = new Query(Criteria.where("_id").is(new ObjectId(objectId)));
                Update updatepublish = new Update();
                updatepublish.set("state", 0);
                mongoTemplate.updateFirst(querypublish, updatepublish, "user_sound");
                redisTemplate.delete("user_soundRepeat_" + myid);
            }
        }
        //================================================================================================
        Query query = new Query(Criteria.where("userId").is(myid).and("likeUserId").is(id));
        //判断如果他也喜欢我则变成好友
        Query query1 = new Query(Criteria.where("userId").is(id).and("friendId").is(myid));
        Query query2 = new Query(Criteria.where("friendId").is(id).and("userId").is(myid));
        Friend one = mongoTemplate.findOne(query1, Friend.class);
        Friend one1 = mongoTemplate.findOne(query2, Friend.class);
        mongoTemplate.remove(query, "user_like");
        if (one1 != null && one != null) {
            mongoTemplate.remove(query1, Friend.class);
            mongoTemplate.remove(query2, Friend.class);
        }
    }

    @Override
    public Boolean idLove(Long id, Long myid) {
        boolean issound = false;
        //获取userlovestate,判断是否访问的是语音的love
        Query queryIsLove = new Query(Criteria.where("userId").is(myid));
        UserLoveState loveState = mongoTemplate.findOne(queryIsLove, UserLoveState.class);
        if (loveState.getIslove() == 1) {
            String soundId = redisTemplate.opsForValue().get("Sound_Linshi_" + myid);
            //如果喜欢则删除总语音表语音，并且删除临时拉黑表记录
           /* Query queryBlackList = new Query(Criteria.where("type").is(2));
            UserSoundBlackList blacksound = mongoTemplate.findOne(queryBlackList, UserSoundBlackList.class, "user_soundBlackList_" + myid);*/
            if (soundId != null) {
                Query querydelPublishSound = new Query(Criteria.where("_id").is(new ObjectId(soundId)));
                mongoTemplate.remove(querydelPublishSound, UserSound.class);
                //mongoTemplate.remove(queryBlackList, "user_soundBlackList_" + myid);
                redisTemplate.delete("Sound_Linshi_" + myid);
                //删除该语音为状态3的语音
                Query queryBlackList2 = new Query(Criteria.where("soundId").is(new ObjectId(soundId)));
                mongoTemplate.remove(queryBlackList2, "user_soundBlackList_" + myid);
            } else {
                //如果blacksound的type为2为空则查找type为3，从redis获取
                String objectId = redisTemplate.opsForValue().get("user_soundRepeat_" + myid);
                Query query = new Query(Criteria.where("soundId").is(new ObjectId(objectId)));
                mongoTemplate.remove(query, "user_soundBlackList_" + myid);
                //查找总表中的路径
                Query querypub=new Query(Criteria.where("_id").is(new ObjectId(objectId)));
                UserSound one = mongoTemplate.findOne(querypub, UserSound.class);
                //删除总表中的语音数据
                Query query1 = new Query(Criteria.where("_id").is(new ObjectId(objectId)));
                mongoTemplate.remove(query1, UserSound.class);
                redisTemplate.delete("user_soundRepeat_" + myid);
                //删除fdfs里面的文件
                StorePath storePath = StorePath.parseFromUrl(one.getPath());
                storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            }
            issound = true;
        }
        //=======================================================================================
        //保存userLike
        UserLike userLike = new UserLike();
        userLike.setUserId(myid);
        userLike.setLikeUserId(id);
        userLike.setCreated(new Date().getTime());
        mongoTemplate.save(userLike, "user_like");
        //通过判断是语音还是普通点击
        if (issound) {
            //判断是否屏蔽通知,不是屏蔽通知就发送
            Settings byUserId = settingsApi.findByUserId(id);
            //发送语音环信
            if (byUserId.getLikeNotification()) {
                AskerVo askerVo = new AskerVo();
                askerVo.setReply("我喜欢你的语音，可以做个朋友吗");
                askerVo.setStrangerQuestion("语音喜欢");
                askerVo.setUserId(myid);
                //查询nicknamem，转换json
                UserInfo byId = userInfoApi.findById(myid);
                askerVo.setNickname(byId.getNickname());
                String s = JSON.toJSONString(askerVo);
                System.out.println("发送的json" + s);
                huanXinTemplate.sendMsg(id.toString(), s);
            }
        } else {
            //判断是否是朋友，不是朋友就发送
            Query queryFriends = new Query(Criteria.where("userId").is(myid).and("friendId").is(id));
            boolean exists = mongoTemplate.exists(queryFriends, Friend.class);
            //判断是否屏蔽通知,不是屏蔽通知就发送
            Settings byUserId = settingsApi.findByUserId(id);
            if (!exists && byUserId.getLikeNotification()) {
                //发送普通喜欢环信
                AskerVo askerVo = new AskerVo();
                askerVo.setReply("我喜欢你的动态，可以做个朋友吗");
                askerVo.setStrangerQuestion("动态喜欢");
                askerVo.setUserId(myid);
                //查询nicknamem，转换json
                UserInfo byId = userInfoApi.findById(myid);
                askerVo.setNickname(byId.getNickname());
                String s = JSON.toJSONString(askerVo);
                System.out.println("发送的json" + s);
                huanXinTemplate.sendMsg(id.toString(), s);
            }
        }
        //判断如果他也喜欢我则变成好友
        Query query = new Query(Criteria.where("userId").is(id).and("likeUserId").is(myid));
        UserLike one = mongoTemplate.findOne(query, UserLike.class);
        if (one != null) {
            long time = new Date().getTime();
            Friend friends = new Friend();
            friends.setCreated(time);
            friends.setUserId(myid);
            friends.setFriendId(id);
            mongoTemplate.save(friends, "tanhua_users");
            Friend friends2 = new Friend();
            friends2.setCreated(time);
            friends2.setUserId(id);
            friends2.setFriendId(myid);
            mongoTemplate.save(friends2, "tanhua_users");
        }
        Query query2 = new Query(Criteria.where("userId").is(id).and("friendId").is(myid));
        Query query1 = new Query(Criteria.where("userId").is(myid).and("friendId").is(id));
        if (mongoTemplate.exists(query1, Friend.class) && mongoTemplate.exists(query2, Friend.class)) {
            return true;
        }
        return false;
    }

    @Override
    public List<TodayBestVo> getRecommendations(long userId, int count) {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("userId").is(userId)),
                Aggregation.sample(count)
        );
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(aggregation, RecommendUser.class, RecommendUser.class);
        List<RecommendUser> recommendUserList = aggregate.getMappedResults();
        List<Long> recommendUserIds = new ArrayList<>();
        recommendUserList.forEach(recommend -> recommendUserIds.add(recommend.getRecommendUserId()));
        List<UserInfo> userInfoList = userInfoApi.findByIds(recommendUserIds);
        ArrayList<TodayBestVo> voList = new ArrayList<>();
        // 封装到Vo
        userInfoList.forEach(userInfo -> {
            TodayBestVo todayBestVo = new TodayBestVo();
            BeanUtils.copyProperties(userInfo, todayBestVo);
            if (userInfo.getTags() != null)
                todayBestVo.setTags(userInfo.getTags().split(","));
            voList.add(todayBestVo);
        });
        return voList;
    }
}
